package org.chnxi.study.leetcode.questions25.ques16;

import java.util.Arrays;

/**
 * 最接近的三数之和
 * 执行用时 :56 ms, 在所有 Java 提交中击败了8.32%的用户
 * 内存消耗 :39.5 MB, 在所有 Java 提交中击败了6.82%的用户
 *
 * 直接使用暴力方法进行三层循环
 */
public class Simple01 {

    public static void main(String[] args) {
        int[] nums1 = {-1,2,1,-4};
        int target1 = 1;
        int result1 = threeSumClosest(nums1 , target1);
        System.out.println("-1 = "+result1);

        int[] nums2 = {1, 1, -1, -1, 3};
        int target2 = -1;
        int result2 = threeSumClosest(nums2 , target2);
        System.out.println("-1 = "+result2);


        int[] nums3 = {-3,-2,-5,3,-4};
        int target3 = -1;
        int result3 = threeSumClosest(nums3 , target3);
        System.out.println("-2 = "+result3);

        int[] nums4 = {-1,2,1,-4};
        int target4 = 1;
        int result4 = threeSumClosest(nums4 , target4);
        System.out.println("2 = "+result4);


    }

    public static int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
            int len = nums.length;
            int result = 1000;
            for (int num1Idx = 0; num1Idx < len-2; num1Idx++){
                for (int num2Idx = num1Idx+1; num2Idx < len-1; num2Idx++){
                    for (int num3Idx = num2Idx+1; num3Idx < len; num3Idx++){
                        int count = nums[num1Idx] + nums[num2Idx] + nums[num3Idx];
                        if(count - target == 0){
                            return count;
                        }
                        if(Math.abs(count - target) < Math.abs(result - target)){
                            result = count;
                        }
                    }
                }
            }
            return result;
    }

}
